﻿using System;
using System.Configuration;
using System.IO;
using System.Web;
using Shuba.Business;
using Shuba.Model;

namespace Shuba.Web.mobile
{
    public partial class upload_apk : basePage
    {
        string msg = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                string acl = GetUserAccess("MSTR_SPADA_FILE_VERSION");

                if (!IsUserAdd(acl))
                {
                    msg = this.GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                    AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
                }


                if (Request.QueryString["a"] == "ed")
                {

                    string version = Request.QueryString["v"];
                    txtVersion.Enabled = false;
                    txtVersion.Text = version;
                }

                LabelTitle.Text = "Upload SPA-MOBILE File";//GetPageTitle("UPLOAD_APK");
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                try
                {
                    Upload();
                    AlertAndRedirect("Upload success!", "apk_list.aspx");
                }
                catch (Exception ex)
                {
                    lblStatus.Text = ex.Message;
                }
            }
        }

        private void Upload()
        {
            if (FileUpload1.HasFile)
            {

                long length = FileUpload1.FileContent.Length;
                string fileName = "SPAMobile_" + txtVersion.Text + ".apk";
                string path = Server.MapPath("~/SPADAApps");
                string filePath = System.IO.Path.Combine(path, fileName);
                FileUpload1.SaveAs(filePath);

                MobileFile bl = new MobileFile();
                MobileFileInfo info = new MobileFileInfo();
                if (!txtVersion.Enabled)
                {
                    info = bl.Get(txtVersion.Text.Trim());
                }
                info.ActType = "UPDATE";
                info.DateFileUpload = DateTime.Now;
                info.FileSizeUpload = length;
                info.PathFileUpload = path;
                info.FileNameUpload = fileName;
                info.NameFolderUpload = "APK";
                if (txtVersion.Enabled)
                {
                    info.Version = txtVersion.Text.Trim();
                    info.EntryBy = User.Identity.Name;
                    info.EntryDate = DateTime.Now;
                    info.ActType = "INSERT";
                }
                info.UpdateBy = User.Identity.Name;
                info.UpdateDate = DateTime.Now;
                info.Checksum = GenerateCheckSum(filePath);

                bl.Save(info);
            }
        }

        public long GenerateCheckSum(string path)
        {
            using (FileStream fs = new FileStream(path, FileMode.Open))
            {
                long length = new FileInfo(path).Length;
                byte[] buffer = new byte[length];
                Adler32 adler = new Adler32();
                fs.Read(buffer, 0, buffer.Length);
                adler.Update(buffer, 0, buffer.Length);
                return adler.Value;
            }
        }
    }

    public sealed class Adler32
    {
        const uint BASE = 65521;

        public long Value
        {
            get
            {
                return checksum;
            }
        }

        public Adler32()
        {
            Reset();
        }

        public void Reset()
        {
            checksum = 1;
        }

        public void Update(int value)
        {
            uint s1 = checksum & 0xFFFF;
            uint s2 = checksum >> 16;

            s1 = (s1 + ((uint)value & 0xFF)) % BASE;
            s2 = (s1 + s2) % BASE;

            checksum = (s2 << 16) + s1;
        }

        public void Update(byte[] buffer)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            Update(buffer, 0, buffer.Length);
        }

        public void Update(byte[] buffer, int offset, int count)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            if (offset < 0)
            {
                throw new ArgumentOutOfRangeException("offset", "cannot be negative");
            }

            if (count < 0)
            {
                throw new ArgumentOutOfRangeException("count", "cannot be negative");
            }

            if (offset >= buffer.Length)
            {
                throw new ArgumentOutOfRangeException("offset", "not a valid index into buffer");
            }

            if (offset + count > buffer.Length)
            {
                throw new ArgumentOutOfRangeException("count", "exceeds buffer size");
            }

            uint s1 = checksum & 0xFFFF;
            uint s2 = checksum >> 16;

            while (count > 0)
            {
                int n = 3800;
                if (n > count)
                {
                    n = count;
                }
                count -= n;
                while (--n >= 0)
                {
                    s1 = s1 + (uint)(buffer[offset++] & 0xff);
                    s2 = s2 + s1;
                }
                s1 %= BASE;
                s2 %= BASE;
            }

            checksum = (s2 << 16) | s1;
        }

        #region Instance Fields
        uint checksum;
        #endregion
    }
}
